﻿Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Interactivity

Public Class BindableColumnHeader
    Inherits Behavior(Of DataGridColumn)
    ''' <summary>
    ''' The <see cref="Header" /> dependency property's name.
    ''' </summary>
    Public Const HeaderPropertyName As String = "Header"

    ''' <summary>
    ''' Gets or sets the value of the <see cref="Header" />
    ''' property. This is a dependency property.
    ''' </summary>
    Public Property Header() As String
        Get
            Return DirectCast(GetValue(HeaderProperty), String)
        End Get
        Set(value As String)
            SetValue(HeaderProperty, value)
        End Set
    End Property

    ''' <summary>
    ''' Identifies the <see cref="Header" /> dependency property.
    ''' </summary>
    Public Shared ReadOnly HeaderProperty As DependencyProperty = DependencyProperty.Register(HeaderPropertyName, GetType(String), GetType(BindableColumnHeader), New PropertyMetadata(New PropertyChangedCallback(AddressOf HandleHeaderBindingChanged)))

    Private Shared Sub HandleHeaderBindingChanged(obj As DependencyObject, args As DependencyPropertyChangedEventArgs)
        Dim behave = TryCast(obj, BindableColumnHeader)
        If behave Is Nothing OrElse behave.AssociatedObject Is Nothing Then
            Return
        End If

        behave.AssociatedObject.Header = args.NewValue
    End Sub

    Protected Overrides Sub OnAttached()
        If Me.AssociatedObject Is Nothing Then
            Return
        End If

        Me.AssociatedObject.Header = Me.Header

        MyBase.OnAttached()
    End Sub
End Class